<template>
  <div v-loading="loading">
    <div class="d-flex mb-3 justify-content-end">
      <div v-show="!editType">
        <button
          v-if="hasFinish"
          class="btn btn-outline-primary"
          :disabled="apiError"
          @click="handlerEdit"
        >
          <i class="fa fa-edit"></i>
          修改
        </button>
      </div>
      <div v-show="editType">
        <button class="btn btn-outline-primary mr-3" @click="editType = false">
          <i class="fa fa-times"></i>
          取消
        </button>
        <button
          class="btn btn-primary"
          :disabled="apiError"
          @click="handlerSave"
          :loading="saveLoading"
        >
          <i class="fa fa-edit"></i>
          保存
        </button>
      </div>
    </div>

    <h5 class="text-center">资产负债表</h5>
    <div class="text-right">单位： （元）</div>

    <table class="table table-bordered text-center">
      <colgroup>
        <col width="20%" />
        <col width="13%" />
        <col width="13%" />
        <col width="14%" />
        <col width="13%" />
        <col width="14%" />
        <col width="13%" />
      </colgroup>
      <tbody>
        <tr>
          <td></td>
          <td class="report-input-td">
            <el-date-picker
              v-if="editType"
              v-model="tableHeader.col2"
              placeholder="选择日期"
              class="w-100"
              align="center"
              type="month"
              :clearable="false"
              value-format="yyyy-MM"
            ></el-date-picker>
            <span v-else>
              <span v-if="tableHeader.col2">
                {{ $utils.dateFormat(getFullDateStr(tableHeader.col2), 'yyyy年M月') }}
              </span>
              <span v-else>-</span>
            </span>
          </td>
          <td class="report-input-td">
            <el-date-picker
              v-if="editType"
              v-model="tableHeader.col3"
              placeholder="选择日期"
              class="w-100"
              align="center"
              type="year"
              :clearable="false"
              :disabled="!tableHeader.col2"
              :picker-options="{ disabledDate: d => disabledDate(d, 2) }"
              value-format="yyyy"
            ></el-date-picker>
            <span v-else>{{ tableHeader.col3 | pureUnit('年') }}</span>
          </td>
          <td class="report-input-td">
            <el-date-picker
              v-if="editType"
              v-model="tableHeader.col4"
              placeholder="选择日期"
              class="w-100"
              align="center"
              type="year"
              :clearable="false"
              :disabled="!tableHeader.col2"
              :picker-options="{ disabledDate: d => disabledDate(d, 2) }"
              value-format="yyyy"
            ></el-date-picker>
            <span v-else>{{ tableHeader.col4 | pureUnit('年') }}</span>
          </td>
          <td>{{ tableHeader.col5 }}</td>
          <td class="report-input-td">
            <el-date-picker
              v-if="editType"
              v-model="tableHeader.col6"
              placeholder="选择日期"
              class="w-100"
              align="center"
              type="year"
              :clearable="false"
              :disabled="!tableHeader.col4"
              :picker-options="{ disabledDate: d => disabledDate(d, 4) }"
              value-format="yyyy"
            ></el-date-picker>
            <span v-else>{{ tableHeader.col6 | pureUnit('年') }}</span>
          </td>
          <td>{{ tableHeader.col7 }}</td>
        </tr>
        <tr v-for="(item, index) in tableData" :key="`edit-${index}`" :class="[item.css || '']">
          <td>{{ item.col1 || '' }}</td>
          <td class="report-input-td">
            <input
              type="number"
              class="form-control text-center"
              @input="handlerChange(item, index, 2)"
              v-if="editType && !item.sumRow"
              v-model="item.col2"
            />
            <span v-else>{{ item.col2 | fixed }}</span>
          </td>
          <td class="report-input-td">
            <input
              type="number"
              class="form-control text-center"
              @input="handlerChange(item, index, 3)"
              v-if="editType && !item.sumRow"
              v-model="item.col3"
            />
            <span v-else>{{ item.col3 | fixed }}</span>
          </td>
          <td class="report-input-td">
            <input
              type="number"
              class="form-control text-center"
              @input="handlerChange(item, index, 4)"
              v-if="editType && !item.sumRow"
              v-model="item.col4"
            />
            <span v-else>{{ item.col4 | fixed }}</span>
          </td>
          <td>{{ item.col5 | fixed }}</td>
          <td class="report-input-td">
            <input
              type="number"
              class="form-control text-center"
              v-if="editType && !item.sumRow"
              @input="handlerChange(item, index, 6)"
              v-model="item.col6"
            />
            <span v-else>{{ item.col6 | fixed }}</span>
          </td>
          <td>{{ item.col7 | fixed }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
<script>
export default {
  components: {},
  props: {},
  data() {
    return {
      relatedId: '',
      customerData: {},
      apiData: [],
      tableData: [],
      tableHeader: {
        col1: '',
        col2: '',
        col3: '',
        col4: '',
        col5: '',
        col6: '',
        col7: '',
      },
      editType: false,
      loading: false,
      saveLoading: false,
      apiError: false,
      isExist: false,
      tableName: 'datum_customer_finance_report',
    }
  },
  computed: {
    hasFinish() {
      return this.customerData.project_status === '0' || this.customerData.project_status === '2'
    },
  },
  watch: {},
  created() {
    this.init()
    this.getData()
  },
  mounted() {},
  methods: {
    init() {
      this.relatedId = this.$route.query.id || sessionStorage.getItem('customer_related_id') || ''
      this.customerData = JSON.parse(sessionStorage.getItem('customer_related_view')) || {}
    },

    async getData() {
      this.loading = true
      const [res, err] = await this.$utils.promise(
        this.$api.getData(
          'credit',
          this.tableName,
          {
            'customer_related_id.eq': this.relatedId,
          },
          { report_date: 'desc' }
        )
      )
      this.loading = false

      if (err) {
        this.apiError = true
        return this.$message.error('获取资产负债表失败，请重试！')
      }
      this.apiError = false

      // 处理不等于4条数据的情况：
      // 1、0条，算添加
      // 2、少于4条，算添加，但先把所有存在的数据删除
      // 3、等于4条，算修改，不做其他操作
      // 4、多于4条，算修改，把剩余的数据删除
      const data = (res && res.data) || []
      let deleteData = []
      if (data.length < 4) {
        this.apiData = [{}, {}, {}, {}]
        this.isExist = false
        deleteData = [...data]
      } else {
        this.apiData = data.slice(0, 4)
        this.isExist = true
        deleteData = data.slice(5)
      }
      this.deleteDatas(deleteData)

      this.tableData = []

      let calcIndex = 0
      const sumArray = [
        [0, 0, 0, 0, 0, 0], // 流动资产小计
        [0, 0, 0, 0, 0, 0], // 固定资产小计
        [0, 0, 0, 0, 0, 0], // 负债小计
        [0, 0, 0, 0, 0, 0], // 权益小计
      ]

      const getCha = (data1, data2) => Math.round((+data2 - +data1) * 100) / 100
      const getRow = (col1 = '', key = '') => {
        const col2 = this.getNum(this.apiData[0][key], true)
        const col3 = this.getNum(this.apiData[1][key], true)
        const col4 = this.getNum(this.apiData[2][key], true)
        const col6 = this.getNum(this.apiData[3][key], true)
        const col5 = getCha(+col4, +col3)
        const col7 = getCha(+col6, +col4)

        // 计算小计
        sumArray[calcIndex][0] += +col2
        sumArray[calcIndex][1] += +col3
        sumArray[calcIndex][2] += +col4
        sumArray[calcIndex][3] += +col5
        sumArray[calcIndex][4] += +col6
        sumArray[calcIndex][5] += +col7

        return { col1, col2, col3, col4, col5, col6, col7, key }
      }
      const pushTable = arr => {
        for (let item of arr) {
          this.tableData.push(getRow(item.label, item.key))
        }
      }
      const pushSumRow = col1 => {
        this.tableData.push({
          col1,
          col2: sumArray[calcIndex][0],
          col3: sumArray[calcIndex][1],
          col4: sumArray[calcIndex][2],
          col5: sumArray[calcIndex][3],
          col6: sumArray[calcIndex][4],
          col7: sumArray[calcIndex][5],
          css: 'font-weight-bold',
          sumRow: true,
        })
      }
      const pushAddRow = (col1, rowIndex1, rowIndex2) => {
        this.tableData.push({
          col1,
          col2: sumArray[rowIndex1][0] + sumArray[rowIndex2][0],
          col3: sumArray[rowIndex1][1] + sumArray[rowIndex2][1],
          col4: sumArray[rowIndex1][2] + sumArray[rowIndex2][2],
          col5: sumArray[rowIndex1][3] + sumArray[rowIndex2][3],
          col6: sumArray[rowIndex1][4] + sumArray[rowIndex2][4],
          col7: sumArray[rowIndex1][5] + sumArray[rowIndex2][5],
          css: 'font-weight-bold',
          sumRow: true,
        })
      }

      // 表头
      this.tableHeader.col1 = ''
      this.tableHeader.col2 = this.apiData[0].report_date
      this.tableHeader.col3 = this.apiData[1].report_date
      this.tableHeader.col4 = this.apiData[2].report_date
      this.tableHeader.col5 = '变动额'
      this.tableHeader.col6 = this.apiData[3].report_date
      this.tableHeader.col7 = '变动额'

      // 流动资产
      calcIndex = 0
      pushTable([
        { label: '货币资金', key: 'currency' },
        { label: '应收账款', key: 'receivables' },
        { label: '预付账款', key: 'pre_charge' },
        { label: '存货', key: 'stock' },
        { label: '其他应收款', key: 'other_receivables' },
        { label: '其他流动资产', key: 'other_current_assets' },
      ])
      pushSumRow('流动资产小计')

      // 固定资产
      calcIndex = 1
      pushTable([
        { label: '长期投资', key: 'long_invest' },
        { label: '固定资产净额', key: 'net_fixed_assets' },
        { label: '在建工程', key: 'const_project' },
        { label: '无形资产净额', key: 'net_intangible_assets' },
      ])
      pushSumRow('固定资产小计')
      pushAddRow('资产合计', 0, 1)

      // 负债
      calcIndex = 2
      pushTable([
        { label: '短期借款', key: 'short_load' },
        { label: '应付账款', key: 'should_charge' },
        { label: '预收账款', key: 'pre_receivables' },
        { label: '其他应付款', key: 'other_should_charge' },
        { label: '其他流动负债', key: 'other_current_debt' },
        { label: '长期负债', key: 'long_debt' },
      ])
      pushSumRow('负债小计')

      // 权益
      calcIndex = 3
      pushTable([
        { label: '实收资本或股本', key: 'paid_capital' },
        { label: '资本公积', key: 'capital_reserve' },
        { label: '留存收益', key: 'retained_earnings' },
        { label: '未分配利润', key: 'und_profit' },
      ])
      pushSumRow('权益小计')
      pushAddRow('负债与所有者权益合计', 2, 3)
    },

    getFix: num => Math.round(num * 100) / 100,

    getNum: (num, mixString) => {
      const v = Number.parseFloat(num)
      return isNaN(v) ? (mixString ? '' : 0) : v
    },

    getUnit: (num, unit) => (num ? `${num}${unit}` : ''),

    handlerChangeValue1(index) {
      this.tableData[index].col5 = this.getFix(
        this.getNum(this.tableData[index].col3) - this.getNum(this.tableData[index].col4)
      )
    },

    handlerChangeValue2(index) {
      this.tableData[index].col7 = this.getFix(
        this.getNum(this.tableData[index].col4) - this.getNum(this.tableData[index].col6)
      )
    },

    handlerChange(item, index, col) {
      if (col === 3) {
        this.handlerChangeValue1(index)
      } else if (col === 6) {
        this.handlerChangeValue2(index)
      } else if (col === 4) {
        this.handlerChangeValue1(index)
        this.handlerChangeValue2(index)
      }

      const rowSum1 = this.getFix(
        this.getNum(this.tableData[0][`col${col}`]) +
          this.getNum(this.tableData[1][`col${col}`]) +
          this.getNum(this.tableData[2][`col${col}`]) +
          this.getNum(this.tableData[3][`col${col}`]) +
          this.getNum(this.tableData[4][`col${col}`]) +
          this.getNum(this.tableData[5][`col${col}`])
      )
      this.tableData[6][`col${col}`] = rowSum1

      const rowSum2 = this.getFix(
        this.getNum(this.tableData[7][`col${col}`]) +
          this.getNum(this.tableData[8][`col${col}`]) +
          this.getNum(this.tableData[9][`col${col}`]) +
          this.getNum(this.tableData[10][`col${col}`])
      )
      this.tableData[11][`col${col}`] = rowSum2
      this.tableData[12][`col${col}`] = this.getFix(rowSum1 + rowSum2)

      const rowSum3 = this.getFix(
        this.getNum(this.tableData[13][`col${col}`]) +
          this.getNum(this.tableData[14][`col${col}`]) +
          this.getNum(this.tableData[15][`col${col}`]) +
          this.getNum(this.tableData[16][`col${col}`]) +
          this.getNum(this.tableData[17][`col${col}`]) +
          this.getNum(this.tableData[18][`col${col}`])
      )
      this.tableData[19][`col${col}`] = rowSum3

      const rowSum4 = this.getFix(
        this.getNum(this.tableData[20][`col${col}`]) +
          this.getNum(this.tableData[21][`col${col}`]) +
          this.getNum(this.tableData[22][`col${col}`]) +
          this.getNum(this.tableData[23][`col${col}`])
      )
      this.tableData[24][`col${col}`] = rowSum4
      this.tableData[25][`col${col}`] = this.getFix(rowSum3 + rowSum4)
    },

    handlerEdit() {
      this.editType = !this.editType
    },

    handlerSave() {
      if (this.apiError) {
        return this.$message.error('资产负债表读取失败，请刷新重试！')
      }

      const data = [{}, {}, {}, {}]
      data[0].report_date = this.tableHeader.col2
      data[1].report_date = this.tableHeader.col3
      data[2].report_date = this.tableHeader.col4
      data[3].report_date = this.tableHeader.col6
      for (let d of this.tableData) {
        if (d.key) {
          if (d.col2) {
            data[0][d.key] = d.col2
          }
          if (d.col3) {
            data[1][d.key] = d.col3
          }
          if (d.col4) {
            data[2][d.key] = d.col4
          }
          if (d.col6) {
            data[3][d.key] = d.col6
          }
        }
      }

      if (this.isExist) {
        this.putData(data)
      } else {
        for (let d of data) {
          d.customer_id = this.customerData.customer_id
          d.customer_related_id = this.relatedId
        }
        this.postData(data)
      }
    },

    async putData(data) {
      this.saveLoading = true
      Promise.all([
        this.eachPut(0, data[0]),
        this.eachPut(1, data[1]),
        this.eachPut(2, data[2]),
        this.eachPut(3, data[3]),
      ])
        .then(() => {
          this.$message.success('数据采集成功！')
          this.getData()
          this.editType = false
        })
        .catch(() => {
          this.$message.error(`数据采集失败，请重试！`)
        })
        .then(() => {
          this.saveLoading = false
        })
    },

    async postData(data) {
      this.saveLoading = true
      const [res, err] = await this.$utils.promise(
        this.$api.addBatch('credit', this.tableName, data)
      )
      this.saveLoading = false

      if (res) {
        this.$message.success('数据采集成功！')
        this.getData()
        this.editType = false
      } else {
        this.$message.error(`数据采集失败，请重试！（${err.status}）`)
      }
    },

    eachPut(i, data) {
      return new Promise((resolve, reject) => {
        this.$api
          .updateData('credit', this.tableName, this.apiData[i].id, data)
          .then(res => {
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    deleteDatas(data = []) {
      for (let d of data) {
        this.$api.deleteData('credit', this.tableName, d.id).then(() => {})
      }
    },

    disabledDate(date, index) {
      let preDate = this.tableHeader[`col${index}`]

      if (!preDate) {
        return true
      }

      preDate = preDate.replace(/^(\d{4}).*/, '$1')
      preDate = Number.parseInt(preDate, 10)
      return isNaN(preDate) ? true : date.getFullYear() >= preDate + (index === 0 ? 1 : 0)
    },

    getFullDateStr(str) {
      if (/^\d{4}-\d{2}$/.test(str)) {
        return `${str}-01`
      }
      return str
    },
  },
  filters: {
    fixed: v => {
      let f = Number.parseFloat(v)
      return isNaN(f) ? '-' : `${f.toFixed(2)}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },
  },
}
</script>
<style scoped lang="scss">
.table-bordered td {
  border-color: #333;
  text-align: center;
  vertical-align: middle;
}
</style>
